<template>
  <div class="athlete-list-container">
    <!-- 页面标题和操作栏 -->
    <div class="page-header">
      <div class="header-title">
        <h2>运动员管理</h2>
        <p>管理系统中的所有运动员信息</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd" v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:add') || hasPermission('athlete')">
          <el-icon><Plus /></el-icon>
          新增运动员
        </el-button>
      
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="学号">
          <el-input 
            v-model="searchForm.studentNumber" 
            placeholder="请输入学号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.realName" 
            placeholder="请输入姓名"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="院系">
          <el-input 
            v-model="searchForm.department" 
            placeholder="请输入院系"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="班级">
          <el-input 
            v-model="searchForm.className" 
            placeholder="请输入班级"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="请选择性别" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="男" :value="0"/>
            <el-option label="女" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option label="全部" :value="null"/>
            <el-option label="正常" :value="1"/>
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card" shadow="never">
      <div class="table-toolbar">
        <div class="toolbar-left">
          <el-button 
            type="danger" 
            :disabled="selectedAthletes.length === 0" 
            @click="handleBatchDelete"
            v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:delete') || hasPermission('athlete')"
          >
            <el-icon><Delete /></el-icon>
            批量删除
          </el-button>
        </div>
        <div class="toolbar-right">
          <el-button @click="loadAthleteList" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <el-table 
        :data="athleteList" 
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="studentNumber" label="学号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="realName" label="姓名" min-width="100" show-overflow-tooltip />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === 0 ? 'primary' : 'danger'" size="small">
              {{ row.gender === 0 ? '男' : '女' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="department" label="院系" min-width="120" show-overflow-tooltip />
        <el-table-column prop="className" label="班级" min-width="120" show-overflow-tooltip />
        <el-table-column prop="height" label="身高(cm)" width="100" />
        <el-table-column prop="weight" label="体重(kg)" width="100" />
        <el-table-column prop="specialty" label="专项" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:edit') || hasPermission('athlete')"
            />
            <el-tag v-else :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              link 
              size="small" 
              @click="handleEdit(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:edit') || hasPermission('athlete')"
            >
              编辑
            </el-button>
            <el-button 
              type="info" 
              link 
              size="small" 
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button 
              type="danger" 
              link 
              size="small" 
              @click="handleDelete(row)"
              v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:delete') || hasPermission('athlete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 运动员表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :before-close="handleDialogClose"
      v-if="userStore.userInfo?.username === 'admin' || hasPermission('athlete:edit') || hasPermission('athlete')"
    >
      <el-form
        ref="athleteFormRef"
        :model="athleteForm"
        :rules="athleteFormRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="studentNumber">
              <el-input 
                v-model="athleteForm.studentNumber" 
                placeholder="请输入学号"
                :disabled="isEdit"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="athleteForm.realName" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="athleteForm.gender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="athleteForm.age" :min="16" :max="35" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="athleteForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="athleteForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="院系" prop="department">
              <el-input v-model="athleteForm.department" placeholder="请输入院系" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="className">
              <el-input v-model="athleteForm.className" placeholder="请输入班级" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="身高(cm)" prop="height">
              <el-input-number v-model="athleteForm.height" :min="140" :max="220" :precision="1" placeholder="请输入身高" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number v-model="athleteForm.weight" :min="40" :max="150" :precision="1" placeholder="请输入体重" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="athleteForm.status">
                <el-radio :label="1">正常</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="专项" prop="specialty">
              <el-input 
                v-model="athleteForm.specialty" 
                type="textarea"
                :rows="2"
                placeholder="请输入擅长的运动项目，多个项目用逗号分隔"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 运动员详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="运动员详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ athleteDetail.studentNumber }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ athleteDetail.realName }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag :type="athleteDetail.gender === 0 ? 'primary' : 'danger'" size="small">
            {{ athleteDetail.gender === 0 ? '男' : '女' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="年龄">{{ athleteDetail.age }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ athleteDetail.phone }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{ athleteDetail.email }}</el-descriptions-item>
        <el-descriptions-item label="院系">{{ athleteDetail.department }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ athleteDetail.className }}</el-descriptions-item>
        <el-descriptions-item label="身高">{{ athleteDetail.height }}cm</el-descriptions-item>
        <el-descriptions-item label="体重">{{ athleteDetail.weight }}kg</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="athleteDetail.status === 1 ? 'success' : 'danger'" size="small">
            {{ athleteDetail.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(athleteDetail.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="专项" :span="2">{{ athleteDetail.specialty }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { 
  getAthleteList, createAthlete, updateAthlete, deleteAthlete, 
  batchDeleteAthletes, toggleAthleteStatus, getAthleteDetail
} from '@/api/athlete'
import {
  Plus, Search, Refresh, Delete, Upload, Download
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 数据状态
const loading = ref(false)
const athleteList = ref([])
const selectedAthletes = ref([])

// 搜索表单
const searchForm = reactive({
  studentNumber: '',
  realName: '',
  department: '',
  className: '',
  gender: null,
  status: null
})

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表单对话框
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentAthleteId = ref(null)
const submitLoading = ref(false)
const athleteFormRef = ref(null)

// 详情对话框
const detailDialogVisible = ref(false)
const athleteDetail = ref({})

// 运动员表单
const athleteForm = reactive({
  studentNumber: '',
  realName: '',
  gender: 0,
  age: null,
  phone: '',
  email: '',
  department: '',
  className: '',
  height: null,
  weight: null,
  specialty: '',
  status: 1
})

// 表单验证规则
const athleteFormRules = {
  studentNumber: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 8, max: 20, message: '学号长度在 8 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 16, max: 35, message: '年龄必须在16-35岁之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入院系', trigger: 'blur' }
  ],
  className: [
    { required: true, message: '请输入班级', trigger: 'blur' }
  ],
  height: [
    { required: true, message: '请输入身高', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入体重', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑运动员' : '新增运动员')

// 权限检查 - 取消权限认证，所有登录用户都可以访问
const hasPermission = (permission) => {
  return true
}

// 时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 加载运动员列表
const loadAthleteList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    }
    const response = await getAthleteList(params)
    athleteList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载运动员列表失败:', error)
    ElMessage.error('加载运动员列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadAthleteList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    studentNumber: '',
    realName: '',
    department: '',
    className: '',
    gender: null,
    status: null
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadAthleteList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadAthleteList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedAthletes.value = selection
}

// 新增运动员
const handleAdd = () => {
  isEdit.value = false
  currentAthleteId.value = null
  resetAthleteForm()
  dialogVisible.value = true
}

// 编辑运动员
const handleEdit = (row) => {
  isEdit.value = true
  currentAthleteId.value = row.id
  Object.assign(athleteForm, {
    ...row,
    height: row.height ? parseFloat(row.height) : null,
    weight: row.weight ? parseFloat(row.weight) : null,
    age: row.age ? parseInt(row.age) : null
  })
  dialogVisible.value = true
}

// 查看详情
const handleViewDetail = async (row) => {
  try {
    const response = await getAthleteDetail(row.id)
    athleteDetail.value = {
      ...response.data,
      height: response.data.height ? parseFloat(response.data.height) : null,
      weight: response.data.weight ? parseFloat(response.data.weight) : null,
      age: response.data.age ? parseInt(response.data.age) : null
    }
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取运动员详情失败:', error)
    ElMessage.error('获取运动员详情失败')
  }
}

// 删除运动员
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除运动员"${row.realName}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteAthlete(row.id)
    ElMessage.success('删除成功')
    loadAthleteList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除运动员失败:', error)
      ElMessage.error('删除运动员失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedAthletes.value.length} 个运动员吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const ids = selectedAthletes.value.map(athlete => athlete.id)
    await batchDeleteAthletes(ids)
    ElMessage.success('批量删除成功')
    loadAthleteList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 状态切换
const handleStatusChange = async (row) => {
  try {
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isAdmin || hasPermission('athlete:edit') || hasPermission('athlete')) {
      // 管理员或有权限的用户允许修改
      await toggleAthleteStatus(row.id, row.status)
      ElMessage.success(`运动员已${row.status === 1 ? '启用' : '禁用'}`)
    } else {
      // 无权限用户不允许修改
      throw new Error('您没有修改运动员状态的权限')
    }
  } catch (error) {
    console.error('更新运动员状态失败:', error)
    ElMessage.error(error.message || '更新运动员状态失败')
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
  }
}

// 导入运动员
const handleImport = () => {
  ElMessage.info('导入功能开发中...')
}

// 导出运动员
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 提交表单
const handleSubmit = async () => {
  if (!athleteFormRef.value) return
  
  try {
    await athleteFormRef.value.validate()
    submitLoading.value = true
    
    const formData = { ...athleteForm }
    
    // 检查是否为管理员账号
    const isAdmin = userStore.userInfo?.username === 'admin'
    
    if (isEdit.value) {
      if (isAdmin || hasPermission('athlete:edit') || hasPermission('athlete')) {
        await updateAthlete(currentAthleteId.value, formData)
        ElMessage.success('更新成功')
      } else {
        throw new Error('您没有编辑运动员的权限')
      }
    } else {
      if (isAdmin || hasPermission('athlete:add') || hasPermission('athlete')) {
        await createAthlete(formData)
        ElMessage.success('创建成功')
      } else {
        throw new Error('您没有创建运动员的权限')
      }
    }
    
    dialogVisible.value = false
    loadAthleteList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = (done) => {
  dialogVisible.value = false
  resetAthleteForm()
  if (typeof done === 'function') {
    done()
  }
}

// 重置表单
const resetAthleteForm = () => {
  Object.assign(athleteForm, {
    studentNumber: '',
    realName: '',
    gender: 0,
    age: null,
    phone: '',
    email: '',
    department: '',
    className: '',
    height: null,
    weight: null,
    specialty: '',
    status: 1
  })
  if (athleteFormRef.value) {
    athleteFormRef.value.resetFields()
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadAthleteList()
})
</script>

<style scoped>
.athlete-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title h2 {
  color: #303133;
  margin: 0 0 8px 0;
  font-size: 24px;
}

.header-title p {
  color: #909399;
  margin: 0;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: -18px;
}

.search-form .el-select {
  min-width: 120px;
}

.table-card {
  margin-bottom: 20px;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .table-toolbar {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
